import React, { memo, useState, useMemo, useReducer } from 'react';
import PropTypes from 'prop-types';
import './Bottom.css';
import { ORDER_DEPART } from './constant';

import classnames from 'classnames';

import Slider from './Slider';

const Filter = memo(function Filter(props) {
  const { name, checked, value, dispatch } = props;
  return (
    <li
      className={classnames({ checked })}
      onClick={() => dispatch({ type: 'toggle', payload: value })}
    >
      {name}
    </li>
  );
});
Filter.propTypes = {
  name: PropTypes.string.isRequired,
  checked: PropTypes.bool.isRequired,
  value: PropTypes.string.isRequired,
  dispatch: PropTypes.func.isRequired,
};

const Options = memo(function Options(props) {
  const { title, options, checkedMap, dispatch } = props;

  // //定义方法改变选中的状态
  // const toggle = useCallback(
  //   (value) => {
  //     const newCheckedMap = { ...checkedMap }
  //     //如果选中的key值存在 则将其删除(不选中没有key值)
  //     if (newCheckedMap[value]) {
  //       delete newCheckedMap[value]
  //     } else {
  //       //如果key值不存在,则将其选中
  //       newCheckedMap[value] = true
  //     }
  //     update(newCheckedMap)
  //   },
  //   [checkedMap]
  // )

  return (
    <div className="option">
      <h3>{title}</h3>
      <ul>
        {options.map((option) => (
          <Filter
            {...option}
            key={option.value}
            dispatch={dispatch}
            checked={option.value in checkedMap}
          />
        ))}
      </ul>
    </div>
  );
});
Options.propTypes = {
  title: PropTypes.string.isRequired,
  options: PropTypes.array.isRequired,
  checkedMap: PropTypes.object.isRequired,
  dispatch: PropTypes.func.isRequired,
};
const checkedReducer = (prevState, action) => {
  console.log('checkedReducer', action);
  const { type, payload } = action;
  switch (type) {
    case 'toggle': {
      const newState = { ...prevState };

      if (payload in newState) {
        delete newState[payload];
      } else {
        newState[payload] = true;
      }
      // console.log(newState);
      return newState;
    }
    case 'reset':
      return {};
    default:
      break;
  }
  return prevState;
};
const BottomModel = memo(function BottomModel(props) {
  const {
    ticketTypes,
    trainTypes,
    departStations,
    arriveStations,
    checkedTicketTypes,
    checkedTrainTypes,
    checkedDepartStations,
    checkedArriveStations,
    departTimeStart,
    departTimeEnd,
    arriveTimeStart,
    arriveTimeEnd,
    setCheckedTicketTypes,
    setCheckedTrainTypes,
    setCheckedDepartStations,
    setCheckedArriveStations,
    setDepartTimeStart,
    setDepartTimeEnd,
    setArriveTimeStart,
    setArriveTimeEnd,
    toggleIsFiltersVisible,
  } = props;

  //useReducer  第一个参数 reducer ,第二个参数要初始化的数据state(同步方式),第三个参数 要初始化的数据 函数(异步方式)
  const [localCheckedTicketTypes, localCheckedTicketTypesDispatch] = useReducer(
    checkedReducer,
    checkedTicketTypes,
    (checkedTicketTypes) => {
      return {
        ...checkedTicketTypes,
      };
    }
  );
  const [localCheckedTrainTypes, localCheckedTrainTypesDispatch] = useReducer(
    checkedReducer,
    checkedTrainTypes,
    (checkedTrainTypes) => {
      return {
        ...checkedTrainTypes,
      };
    }
  );
  const [
    localCheckedDepartStations,
    localCheckedDepartStationsDispatch,
  ] = useReducer(
    checkedReducer,
    checkedDepartStations,
    (checkedDepartStations) => {
      return {
        ...checkedDepartStations,
      };
    }
  );
  const [
    localCheckedArriveStations,
    localCheckedArriveStationsDispatch,
  ] = useReducer(
    checkedReducer,
    checkedArriveStations,
    (checkedArriveStations) => {
      return {
        ...checkedArriveStations,
      };
    }
  );

  const [localDepartTimeStart, setLocalDepartTimeStart] = useState(
    departTimeStart
  );
  const [localDepartTimeEnd, setLocalDepartTimeEnd] = useState(departTimeEnd);
  const [localArriveTimeStart, setLocalArriveTimeStart] = useState(
    arriveTimeStart
  );
  const [localArriveTimeEnd, setLocalArriveTimeEnd] = useState(arriveTimeEnd);

  const optionGroup = [
    {
      title: '坐席类型',
      options: ticketTypes,
      checkedMap: localCheckedTicketTypes,
      dispatch: localCheckedTicketTypesDispatch,
    },
    {
      title: '车次类型',
      options: trainTypes,
      checkedMap: localCheckedTrainTypes,
      dispatch: localCheckedTrainTypesDispatch,
    },
    {
      title: '出发车站',
      options: departStations,
      checkedMap: localCheckedDepartStations,
      dispatch: localCheckedDepartStationsDispatch,
    },
    {
      title: '到达车站',
      options: arriveStations,
      checkedMap: localCheckedArriveStations,
      dispatch: localCheckedArriveStationsDispatch,
    },
  ];

  const sure = () => {
    setCheckedTicketTypes(localCheckedTicketTypes);
    setCheckedTrainTypes(localCheckedTrainTypes);
    setCheckedDepartStations(localCheckedDepartStations);
    setCheckedArriveStations(localCheckedArriveStations);

    //
    setDepartTimeStart(localDepartTimeStart);
    setDepartTimeEnd(localDepartTimeEnd);
    setArriveTimeStart(localArriveTimeStart);
    setArriveTimeEnd(localArriveTimeEnd);
    toggleIsFiltersVisible();
  };
  //设置重置按钮是否禁用,如果当前筛选条件是初始化的条件,则不需要重置,禁用重置按钮
  const isResetDisabled = useMemo(() => {
    return (
      Object.keys(localCheckedTicketTypes).length === 0 &&
      Object.keys(localCheckedTrainTypes).length === 0 &&
      Object.keys(localCheckedDepartStations).length === 0 &&
      Object.keys(localCheckedArriveStations).length === 0 &&
      localDepartTimeStart === 0 &&
      localDepartTimeEnd === 24 &&
      localArriveTimeStart === 0 &&
      localArriveTimeEnd === 24
    );
  }, [
    localArriveTimeEnd,
    localArriveTimeStart,
    localCheckedArriveStations,
    localCheckedDepartStations,
    localCheckedTicketTypes,
    localCheckedTrainTypes,
    localDepartTimeEnd,
    localDepartTimeStart,
  ]);

  // console.log('isResetDisabled:' + isResetDisabled)

  const reset = () => {
    if (isResetDisabled) {
      return;
    }
    localCheckedTicketTypesDispatch({ type: 'reset' });
    localCheckedTrainTypesDispatch({ type: 'reset' });
    localCheckedDepartStationsDispatch({ type: 'reset' });
    localCheckedArriveStationsDispatch({ type: 'reset' });

    //
    setLocalDepartTimeStart(0);
    setLocalDepartTimeEnd(24);
    setLocalArriveTimeStart(0);
    setLocalArriveTimeEnd(24);
  };
  return (
    <div className="bottom-modal">
      {/* 综合筛选弹窗 */}
      <div className="bottom-dialog">
        {/* 底部 */}
        <div className="bottom-dialog-content">
          <div className="title">
            <span
              className={classnames('reset', {
                disabled: isResetDisabled,
              })}
              onClick={reset}
            >
              重置
            </span>
            <span className="ok" onClick={sure}>
              确定
            </span>
          </div>
          <div className="options">
            {optionGroup.map((group) => {
              return <Options {...group} key={group.title} />;
            })}
          </div>
          <Slider
            title="出发时间"
            currentStartHours={localDepartTimeStart}
            currentEndHours={localDepartTimeEnd}
            onStartChanged={setLocalDepartTimeStart}
            onEndChanged={setLocalDepartTimeEnd}
          />
          <Slider
            title="到达时间"
            currentStartHours={localArriveTimeStart}
            currentEndHours={localArriveTimeEnd}
            onStartChanged={setLocalArriveTimeStart}
            onEndChanged={setLocalArriveTimeEnd}
          />
        </div>
      </div>
    </div>
  );
});
BottomModel.propTypes = {
  ticketTypes: PropTypes.array.isRequired,
  trainTypes: PropTypes.array.isRequired,
  departStations: PropTypes.array.isRequired,
  arriveStations: PropTypes.array.isRequired,
  checkedTicketTypes: PropTypes.object.isRequired,
  checkedTrainTypes: PropTypes.object.isRequired,
  checkedDepartStations: PropTypes.object.isRequired,
  checkedArriveStations: PropTypes.object.isRequired,
  departTimeStart: PropTypes.number.isRequired,
  departTimeEnd: PropTypes.number.isRequired,
  arriveTimeStart: PropTypes.number.isRequired,
  arriveTimeEnd: PropTypes.number.isRequired,
  setCheckedTicketTypes: PropTypes.func.isRequired,
  setCheckedTrainTypes: PropTypes.func.isRequired,
  setCheckedDepartStations: PropTypes.func.isRequired,
  setCheckedArriveStations: PropTypes.func.isRequired,
  setDepartTimeStart: PropTypes.func.isRequired,
  setDepartTimeEnd: PropTypes.func.isRequired,
  setArriveTimeStart: PropTypes.func.isRequired,
  setArriveTimeEnd: PropTypes.func.isRequired,
  toggleIsFiltersVisible: PropTypes.func.isRequired,
};

export default function Bottom(props) {
  const {
    highSpeed,
    orderType,
    onlyTickets,
    isFilterVisible,
    toggleHighSpeed,
    toggleIsFiltersVisible,
    toggleOnlyTickets,
    toggleOrderType,
    ticketTypes, //坐席  数组
    trainTypes, //车次  数组
    departStations, //出发车站  数组
    arriveStations, //到达车站  数组
    checkedTicketTypes, //选中的坐席类型
    checkedTrainTypes, //选中的车次类型
    checkedDepartStations, //选中的出发车站
    checkedArriveStations, // 选中的到达车站
    departTimeStart, //出发时间  开始时间
    departTimeEnd, //出发时间   截止时间
    arriveTimeStart, //到达时间  开始时间
    arriveTimeEnd, //到达时间    截止时间
    //和综合浮层 相关
    setCheckedTicketTypes,
    setCheckedTrainTypes,
    setCheckedDepartStations,
    setCheckedArriveStations,
    setDepartTimeStart,
    setDepartTimeEnd,
    setArriveTimeStart,
    setArriveTimeEnd,
  } = props;

  //综合筛选是否存在筛选条件
  const noCheck = useMemo(() => {
    return (
      Object.keys(checkedTicketTypes).length === 0 &&
      Object.keys(checkedTrainTypes).length === 0 &&
      Object.keys(checkedDepartStations).length === 0 &&
      Object.keys(checkedArriveStations).length === 0 &&
      departTimeStart === 0 &&
      departTimeEnd === 24 &&
      arriveTimeStart === 0 &&
      arriveTimeEnd === 24
    );
  }, [
    arriveTimeEnd,
    arriveTimeStart,
    checkedArriveStations,
    checkedDepartStations,
    checkedTicketTypes,
    checkedTrainTypes,
    departTimeEnd,
    departTimeStart,
  ]);
  // console.log('onCheck:' + noCheck)

  return (
    <div className="bottom">
      {/* tab  */}
      <div className="bottom-filters">
        <span className="item" onClick={toggleOrderType}>
          <i className="icon">&#xf065;</i>
          {orderType === ORDER_DEPART ? '出发 早→ 晚' : '耗时  短→ 长'}
        </span>

        <span
          className={classnames('item', { 'item-on': highSpeed })}
          onClick={toggleHighSpeed}
        >
          <i className="icon">{highSpeed ? '\uf43f' : '\uf43e'}</i>
          只看高铁动车
        </span>

        <span
          className={classnames('item', { 'item-on': onlyTickets })}
          onClick={toggleOnlyTickets}
        >
          <i className="icon">{onlyTickets ? '\uf43d' : '\uf43c'}</i>
          只看有票
        </span>
        {/* 浮动层显示 或者 有筛选条件 则显示选中颜色 */}
        <span
          className={classnames('item', {
            'item-on': isFilterVisible || !noCheck,
          })}
          onClick={toggleIsFiltersVisible}
        >
          {/* 如果 没有选中 则显示 原来样式 如果选中了,则在右上角显示标识选中样式*/}
          <i className="icon">{noCheck ? '\uf0f7' : '\uf446'}</i>
          综合筛选
        </span>
      </div>
      {isFilterVisible && (
        <BottomModel
          ticketTypes={ticketTypes} //坐席  数组
          trainTypes={trainTypes} //车次  数组
          departStations={departStations} //出发车站  数组
          arriveStations={arriveStations} //到达车站  数组
          checkedTicketTypes={checkedTicketTypes} //选中的坐席类型
          checkedTrainTypes={checkedTrainTypes} //选中的车次类型
          checkedDepartStations={checkedDepartStations} //选中的出发车站
          checkedArriveStations={checkedArriveStations} // 选中的到达车站
          departTimeStart={departTimeStart} //出发时间  开始时间
          departTimeEnd={departTimeEnd} //出发时间   截止时间
          arriveTimeStart={arriveTimeStart} //到达时间  开始时间
          arriveTimeEnd={arriveTimeEnd} //到达时间    截止时间
          //和综合浮层 相关
          setCheckedTicketTypes={setCheckedTicketTypes}
          setCheckedTrainTypes={setCheckedTrainTypes}
          setCheckedDepartStations={setCheckedDepartStations}
          setCheckedArriveStations={setCheckedArriveStations}
          setDepartTimeStart={setDepartTimeStart}
          setDepartTimeEnd={setDepartTimeEnd}
          setArriveTimeStart={setArriveTimeStart}
          setArriveTimeEnd={setArriveTimeEnd}
          // 点击确定按钮后 会关闭 综合浮层 所以需要用到这个按钮
          toggleIsFiltersVisible={toggleIsFiltersVisible}
        />
      )}
    </div>
  );
}
Bottom.propTypes = {
  highSpeed: PropTypes.bool.isRequired,
  orderType: PropTypes.number.isRequired,
  onlyTickets: PropTypes.bool.isRequired,
  isFilterVisible: PropTypes.bool.isRequired,
  toggleHighSpeed: PropTypes.func.isRequired,
  toggleIsFiltersVisible: PropTypes.func.isRequired,
  toggleOnlyTickets: PropTypes.func.isRequired,
  toggleOrderType: PropTypes.func.isRequired,

  ticketTypes: PropTypes.array.isRequired, //坐席  数组
  trainTypes: PropTypes.array.isRequired, //车次  数组
  departStations: PropTypes.array.isRequired, //出发车站  数组
  arriveStations: PropTypes.array.isRequired, //到达车站  数组
  checkedTicketTypes: PropTypes.object.isRequired, //选中的坐席类型
  checkedTrainTypes: PropTypes.object.isRequired, //选中的车次类型
  checkedDepartStations: PropTypes.object.isRequired, //选中的出发车站
  checkedArriveStations: PropTypes.object.isRequired, // 选中的到达车站
  departTimeStart: PropTypes.number.isRequired, //出发时间  开始时间
  departTimeEnd: PropTypes.number.isRequired, //出发时间   截止时间
  arriveTimeStart: PropTypes.number.isRequired, //到达时间  开始时间
  arriveTimeEnd: PropTypes.number.isRequired, //到达时间    截止时间
  //和综合浮层 相关
  setCheckedTicketTypes: PropTypes.func.isRequired,
  setCheckedTrainTypes: PropTypes.func.isRequired,
  setCheckedDepartStations: PropTypes.func.isRequired,
  setCheckedArriveStations: PropTypes.func.isRequired,
  setDepartTimeStart: PropTypes.func.isRequired,
  setDepartTimeEnd: PropTypes.func.isRequired,
  setArriveTimeStart: PropTypes.func.isRequired,
  setArriveTimeEnd: PropTypes.func.isRequired,
};
